/*!
 * KAPlayer.js
 */
var KAPlayer = new Object();
KAPlayer.tabs = {
    playlist:   0,
    recommend:  1
};
KAPlayer.mode = {
    order:      1,
    random:     2,
    cycle:      3
};
// Init Functions
KAPlayer.initMarquee = function() {
    var direction = 1;
    setInterval(function() {
        if ($("#info span").width() < $("#info").width()) {
            $("#info").scrollLeft(0);
        } else {
            if ($("#info").scrollLeft() <= 0) {
                direction = 1;
            } else if ($("#info").scrollLeft() >= $("#info span").width()-$("#info").width()) {
                direction = -1;
            }
            $("#info").scrollLeft($("#info").scrollLeft() + direction);
        }
    }, 100);
};
KAPlayer.initProgress = function() {
    KAPlayer.progress = new KASlider({
        range: $("#progress-range"),
        route: $("#progress-route"),
        bar: $("#progress-bar"),
        overflow: false,
        onClick: function(settings) {
            if (KAPlayer.moveEnabled && KAPlayer.seekable()) {
                KAPlayer.player.seek(KAPlayer.player.duration*settings.progress);
            }
        },
        onMouseDown: function(settings) {
            if (KAPlayer.moveEnabled) {
                KAPlayer.moveProgress = true;
                return true;
            }
            return false;
        },
        onMoveStart: function(settings) {
            return KAPlayer.moveEnabled;
        },
        onMoveEnd: function(settings) {
            $("#start").text(KAPlayer.getFormatTime(KAPlayer.player.duration*settings.progress));
        },
        onMouseUp: function(settings) {
            if (KAPlayer.moveEnabled && KAPlayer.seekable()) {
                KAPlayer.player.seek(KAPlayer.player.duration*settings.progress);
            }
            KAPlayer.moveProgress = false;
        }
    });
};
KAPlayer.getFormatTime = function(second) {
    if (isNaN(second)) {
        return "00:00";
    } else {
        var current = (parseInt(second/60) < 10 ? "0" : "") + parseInt(second/60);
        current += ":";
        current += (parseInt(second%60) < 10 ? "0" : "") + parseInt(second%60);
        return current;
    }
};
KAPlayer.initPlayPause = function() {
    $("#play-pause").click(function() {
        if (KAPlayer.index == -1) {
            KAPlayer.playNext();
        } else if (KAPlayer.index == KAPlayer.count) {
            KAPlayer.playPrevious();
        } else {
            if (KAPlayer.player.playing) {
                $(this).attr("title", "播放");
                $(this).removeClass();
                KAPlayer.player.pause();
            } else {
                $(this).attr("title", "暂停");
                $(this).removeClass();
                $(this).addClass("play-pause");
                KAPlayer.player.play();
                KAPlayer.playEnabled = true;
            }
        }
    });
    $("#play-pause").bind("mouseenter", function() {
        if ($(this)[0].className.indexOf("play-pause") > -1) {
            $(this).addClass("pause");
        } else {
            $(this).addClass("play");
        }
    });
    $("#play-pause").bind("mouseleave", function() {
        if ($(this)[0].className.indexOf("play-pause") > -1) {
            $(this).removeClass("pause");
        } else {
            $(this).removeClass("play");
        }
    });
};
KAPlayer.initStop = function() {
    $("#stop").click(function() {
        KAPlayer.playEnabled = false;
        try {
            KAPlayer.player.stop();
        } catch (e) {
            //KAPlayer.player.pause();
            //console.error(e);
        }
    });
    $("#stop").bind("mouseenter mouseleave", function() {
        $(this).toggleClass("stop");
    });
};
KAPlayer.initPreviousNext = function() {
    $("#previous").click(function() {
        KAPlayer.playPrevious();
    });
    $("#previous").bind("mouseenter mouseleave", function() {
        $(this).toggleClass("previous-next");
        $("#previous-next").toggleClass("previous");
    });
    $("#next").click(function() {
        KAPlayer.playNext();
    });
    $("#next").bind("mouseenter mouseleave", function() {
        $(this).toggleClass("previous-next");
        $("#previous-next").toggleClass("next");
    });
};
KAPlayer.initVolume = function() {
    KAPlayer.volume = new KASlider({
        range: $("#volume-range"),
        route: $("#volume-route"),
        bar: $("#volume-bar"),
        overflow: false,
        progress: 1,
        onMoveEnd: function(settings) {
            if (KAPlayer.player.loaded) {
                KAPlayer.player.volume(settings.progress);
                $("#volume-bar").attr("title", Math.floor(settings.progress*100) + "%");
            }
        }
    });

    $("#minus").bind("mouseenter mouseleave", function() {
        $(this).toggleClass("minus");
    });
    $("#add").bind("mouseenter mouseleave", function() {
        $(this).toggleClass("add");
    });
    $("#minus").click(function() {
        adjustVolume(-1);
    });
    $("#add").click(function() {
        adjustVolume(1);
    });

    function adjustVolume(value) {
        var sound = KAPlayer.player.volume();
        sound += value/100;
        if (value <= 0 && sound <= 0) {
            sound = 0;
        } else if(sound >= 1) {
            sound = 1;
        }
        KAPlayer.player.volume(sound);
        $("#volume-bar").attr("title", Math.floor(sound*100) + "%");
        KAPlayer.volume.moveTo(sound);
    }
};
KAPlayer.initPlaylist = function() {
    $(".layout .tab li").each(function() {
        $(this).click(function() {
            $(".layout .tab li").removeClass("hover");
            $(this).addClass("hover");
            $(".layout .playlist").removeClass("hover");
            $(".layout .playlist:eq(" + $(this).index() + ")").addClass("hover");
        });
    });
    loadXML(KAPlayer.baseUrl + "/xml/playlist.xml", KAPlayer.tabs.playlist);
    loadXML(KAPlayer.baseUrl + "/xml/recommend.xml", KAPlayer.tabs.recommend);
    function loadXML(file, tab) {
        var playlist = "<table style='width:100%'>";
        jQuery.ajax({
            url: file,
            async: false,
            cache: false,
            dataType: "XML",
            success: function(xml) {
                $("music", xml).each(function(i) {
                    playlist += "<tr title='" + $(this).children("name").text() + "'>";
                    switch(tab) {
                        case KAPlayer.tabs.playlist:
                            playlist += "<td width='10%'><input type='checkbox' onfocus='this.blur()'></td>";
                            break;
                        case KAPlayer.tabs.recommend:
                            playlist += "<td width='10%' align='right'>" + (i+1) + "&nbsp;&nbsp;&nbsp;&nbsp;</td>";
                            break;
                        default:break;
                    }
                    playlist += "<td width='90%'>" + $(this).children("name").text() + "</td>";
                    playlist += "<td style='display:none'>" + $(this).children("url").text() + "</td>";
                    playlist += "</tr>";
                });
            }
        });
        playlist += "</table>";
        $(".layout .playlist:eq(" + tab + ")").append(playlist);
        KAPlayer.count = $(".layout .playlist:eq(" + tab + ") table tr").length;
        $(".layout .playlist:eq(" + tab + ") table tr").each(function() {
            $(this).dblclick(function() {
                KAPlayer.autoPlay($(this).prevAll().length, tab);
            });
        });
        $(".layout .playlist:eq(" + tab + ") table tr").bind("mouseenter mouseleave", function() {
            $(this).toggleClass("hover");
        });
    }
};
KAPlayer.initAction = function() {
    $("#all").focus(function() {
        $(this).blur();
    });
    $("#all").click(function() {
        $(".layout .playlist:eq(0) input").prop("checked", $(this).prop("checked"));
    });
    $("#remove").click(function() {
        if ($(".layout .playlist:eq(0) input:checked").length == 0) {
            alert("请选择您要移除的歌曲！");
        } else {
            if (window.confirm("您确定要移除这些歌曲吗？")) {
                $(".layout .playlist:eq(0) table tr").each(function(i) {
                    if ($(this).find("input").prop("checked")) {
                        $(this).remove();
                        if (KAPlayer.index >= i) {
                            KAPlayer.index--;
                        }
                    }
                });
                if (KAPlayer.playTab == KAPlayer.tabs.playlist) {
                    KAPlayer.count = $(".layout .playlist:eq(0) table tr").length;
                }
            }
        }
    });
    $("#append").click(function() {
        $("#player .append").show();
        $("#clear").click();
        $("[name='name']").focus();
    });
    $("#close").click(function() {
        $("#player .append").hide();
    });
    $("#close").focus(function() {
        $(this).blur();
    });
    $("#confirm").click(function() {
        $("[name='name']").val($.trim($("[name='name']").val()));
        $("[name='url']").val($.trim($("[name='url']").val()));
        if ($("[name='name']").val() == "") {
            alert("请您输入歌曲名！");
            $("[name='name']").focus();
        } else if ($("[name='url']").val() == "") {
            alert("请您输入链接地址！");
            $("[name='url']").focus();
        } else {
            $("#player .append").hide();
            var music = $("<tr title='" + $("[name='name']").val() + "'>"
                        + "<td width='10%'><input type='checkbox' onfocus='this.blur()'></td>"
                        + "<td width='90%'>" + $("[name='name']").val() + "</td>"
                        + "<td style='display:none'>" + $("[name='url']").val() + "</td>"
                        + "</tr>");
            music.bind("mouseenter mouseleave", function() {
                $(this).toggleClass("hover");
            });
            var length = $(".layout .playlist:eq(0) table tr").length;
            music.dblclick(function() {
                KAPlayer.autoPlay(length, KAPlayer.tabs.playlist);
            });
            music.appendTo($(".layout .playlist:eq(0) table"));
            if (KAPlayer.playTab == KAPlayer.tabs.playlist) {
                KAPlayer.count = length + 1;
            }
        }
    });
    $("#clear").click(function() {
        $("[name='name']").val("");
        $("[name='url']").val("http://");
        $("[name='name']").focus();
    });
};
KAPlayer.initPlayMode = function() {
    $("#order").click(function() {
        $(this).parent().children(".sort").removeClass("hover");
        $(this).addClass("hover");
        KAPlayer.playMode = KAPlayer.mode.order;
    });
    $("#random").click(function() {
        $(this).parent().children(".sort").removeClass("hover");
        $(this).addClass("hover");
        KAPlayer.playMode = KAPlayer.mode.random;
    });
    $("#cycle").click(function() {
        $(this).parent().children(".sort").removeClass("hover");
        $(this).addClass("hover");
        KAPlayer.playMode = KAPlayer.mode.cycle;
    });
};
// Play Functions
KAPlayer.playPrevious = function() {
    switch(KAPlayer.playMode) {
        case KAPlayer.mode.order://order
            if (--KAPlayer.index >= 0) {
                KAPlayer.autoPlay(KAPlayer.index);
            } else if (++KAPlayer.index < 0) {
                KAPlayer.index = -1;
            }
            break;
        case KAPlayer.mode.random://random
            var index = KAPlayer.index;
            if (KAPlayer.count > 1) {
                do {
                    KAPlayer.index = Math.floor(Math.random()*KAPlayer.count);
                } while (index == KAPlayer.index);
            }
            KAPlayer.autoPlay(KAPlayer.index);
            break;
        case KAPlayer.mode.cycle://cycle
            KAPlayer.autoPlay(KAPlayer.index);
            break;
        default:break;
    }
};
KAPlayer.playNext = function() {
    switch(KAPlayer.playMode) {
        case KAPlayer.mode.order://order
            if (++KAPlayer.index < KAPlayer.count) {
                KAPlayer.autoPlay(KAPlayer.index);
            } else {//over
                KAPlayer.index = KAPlayer.count;
                //$("#stop").click();
                KAPlayer.playEnabled = false;
                KAPlayer.reset();
            }
            break;
        case KAPlayer.mode.random://random
            var index = KAPlayer.index;
            if (KAPlayer.count > 1) {
                do {
                    KAPlayer.index = Math.floor(Math.random()*KAPlayer.count);
                } while (index == KAPlayer.index);
            }
            KAPlayer.autoPlay(KAPlayer.index);
            break;
        case KAPlayer.mode.cycle://cycle
            KAPlayer.autoPlay(KAPlayer.index);
            break;
        default:break;
    }
};
KAPlayer.autoPlay = function(index, playTab) {
    if (playTab || playTab == 0) {
        KAPlayer.playTab = playTab;
    }
    KAPlayer.index = index;
    var playlist = $(".layout .playlist:eq(" + KAPlayer.playTab + ")");
    var info = playlist.find("table tr:eq(" + index + ")");
    KAPlayer.info = info.find("td:eq(1)").text();
    KAPlayer.player.load(info.find("td:eq(2)").text());
    playlist.find("table tr").removeClass("play");
    info.addClass("play");
    KAPlayer.count = playlist.find("table tr").length;
    $("#stop").click();
    $("#play-pause").click();
    if (info.position().top <= 0) {
        playlist.scrollTop(playlist.scrollTop() - Math.abs(info.position().top));
    } else if (info.position().top+info.height() >= playlist.height()) {
        playlist.scrollTop(playlist.scrollTop() + info.position().top - playlist.height() + info.height());
    }
};
KAPlayer.reset = function(ended) {
    if (KAPlayer.playEnabled) {
        KAPlayer.playNext();
    } else {
        $("#play-pause").attr("title", "播放");
        $("#play-pause").removeClass();
        // reset
        KAPlayer.progress.moveTo(0);
        $("#start").text("");
        if (ended) {
            $("#info span").text("停止播放：" + KAPlayer.info);
        } else {
            $("#info span").text("");
            $(".layout .playlist:eq(" + KAPlayer.playTab + ") table tr").removeClass("play");
        }
        $("#end").text("");
    }
};
KAPlayer.seekable = function() {
    var userAgent = navigator.userAgent.toLowerCase();
    var audioSeekable = false;
    if (/msie/.test(userAgent) || /trident/.test(userAgent)) {
        audioSeekable = true;
    } else if (/firefox/.test(userAgent)) {
        audioSeekable = true;
    } else if (/opera/.test(userAgent)) {
        audioSeekable = false;
    } else if (/webkit/.test(userAgent)) {
        audioSeekable = false;
    }
    if (audioSeekable) {
        if (KAPlayer.player.audio) {
            return KAPlayer.player.audio.seekable;
        }
    } else {
        return KAPlayer.player.seekable;
    }
    return audioSeekable;
};
KAPlayer.audioReady = function(player) {
    this.on('canplay', function() {
        this.loaded = true;
    }, this);
    this.on('play', function () {
        if (!KAPlayer.moveProgress) {
            var progress = KAPlayer.player.position/KAPlayer.player.duration;
            KAPlayer.progress.moveTo(progress);
        }
        $("#info span").text("正在播放：" + KAPlayer.info);
    }, this);
    this.on('pause', function () {
        if (KAPlayer.playEnabled) {
            $("#info span").text("暂停播放：" + KAPlayer.info);
        }
    }, this);
    this.on('ended', function () {
        KAPlayer.reset(true);
    }, this);
    this.on('timeupdate', function (position, duration) {
        if (KAPlayer.playEnabled) {
            KAPlayer.moveEnabled = true;
            if (position == 0) {
                $("#start").text("00:00");
                KAPlayer.progress.moveTo(0);
                KAPlayer.moveEnabled = false;
            } else if (!KAPlayer.moveProgress) {
                $("#start").text(KAPlayer.getFormatTime(position));
                KAPlayer.progress.moveTo(position/duration);
            }
            $("#info span").text("正在播放：" + KAPlayer.info);
            $("#end").text(KAPlayer.getFormatTime(duration));
        }
    }, this);
    this.on('progress', function (load_percent) {
        if (KAPlayer.playEnabled && !KAPlayer.player.playing) {
            $("#info span").text("缓冲处理：" + load_percent + "%");
        }
    }, this);
    this.on('error', function (error) {
        console.log(error.message);
    }, this);
};
// Initialize
KAPlayer.initPlayer = function(settings) {
    settings = jQuery.extend({
        baseUrl: "kaplayer",
        codecs: ["mp3", "vorbis", "opus", "webm", "wav"],
        throwErrors: true,
    }, settings);
    KAPlayer.baseUrl = settings.baseUrl;
    KAPlayer.index = -1;
    KAPlayer.count = 0;
    KAPlayer.info = "";
    KAPlayer.player = new Audio5js({
        loaded: false,
        swf_path: KAPlayer.baseUrl + "/lib/audio5js/audio5js.swf",
        codecs: settings.codecs,
        throw_errors: settings.throwErrors,
        format_time: false,
        ready: KAPlayer.audioReady 
    });
    KAPlayer.progress = null;
    KAPlayer.volume = null;
    KAPlayer.playEnabled = false;
    KAPlayer.moveEnabled = false;
    KAPlayer.moveProgress = false;
    KAPlayer.playTab = KAPlayer.tabs.playlist;
    KAPlayer.playMode = KAPlayer.mode.order;
    KAPlayer.initMarquee();
    KAPlayer.initProgress();
    KAPlayer.initPlayPause();
    KAPlayer.initStop();
    KAPlayer.initPreviousNext();
    KAPlayer.initVolume();
    KAPlayer.initPlaylist();
    KAPlayer.initAction();
    KAPlayer.initPlayMode();
    jQuery("#player div:not(.append)").bind("selectstart", function() {
        return false;
    });
};
